package com.lewis.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lewis.entry.User;
import com.lewis.mapper.UserMapper;
import com.lewis.vo.UserVo;

@Service
@CacheConfig(cacheNames="userCache")
public class UserServiceImpl implements UserService {
	
	
	 @Resource
	 private UserMapper userMapper;
	
	 @Transactional
	 public void addUserAndRole(UserVo user) throws Exception{
		 //插入user
		 userMapper.addUser(user);
		 //为其配置role
		 userMapper.setRole(user);
		 
	 }
	 
	 /**
	  * 用到了注解@CacheConfig，@CachePut，@Cacheable
       @CachePut 是先执行方法，然后把返回值保存或更新到缓存中
       @Cacheable 是先查询缓存，如果缓存有值，则不执行方法了；否则执行方法，然后把返回值保存到缓存
	  */
	 
	 
	 /**
	  * 将方法第一个参数的username属性作为key，方法的返回值作为value 缓存进redis(新增进缓存)
	  * @param u
	  * @return
	 * @throws Exception 
	  */
     @CachePut(key="#p0.username")
	 public List<User> testAddUserToCache(User u) throws Exception{
    	 
    	 userMapper.addUser(u);
		 
		 return userMapper.getUser(u.getUsername());
	 }
     
     
     /**
      * 先查询缓存通过key查找value，如果缓存中存在则不执行此方法(查询缓存)
      * @param username
      * @return
     * @throws Exception 
      */
     @RequiresPermissions("user:bbb")
     @Cacheable(key="#p0")
     public List<User> getUserFromCache(String username) throws Exception{
    	 System.out.println("执行sql从数据库mysql中查询");
    	 return userMapper.getUser(username);
     }
     
     
     /**
      * 删除一个对象的时候 将对应的缓存中的key删除
      * @param username
      */
     @CacheEvict(key="#p0")
     @Transactional
     public void testDeleteCache(String username) throws Exception{
    	 
    	 //先删除user表，再删除对应的role
    	 userMapper.deleteUser(username); 
    	 userMapper.deleteUserRole(username);
     }
     
     /**
      * 删除缓存中所有的key
      */
     @CacheEvict(allEntries=true)
     public void testDeleteAllFromCache() throws Exception{
    	 
    	 
     }
     
}
